const express = require('express')
//创建一个路由
const route = express.Router()
//引入path
const path = require("path")
//引入权限校验中间件
const isLoginMiddle = require("../middleware/isLoginMiddle")
//引入数据库集合
const advModel = require("../db/model/advModel")
//引入fromData格式的解析器
const formidable=require('formidable')
//添加管理员接口(添加正则校验中间件)
route.post("/addAdv", isLoginMiddle, async (req, res) => {
  const form=formidable({//formidable调用,可以接受fromData格式中携带的文件,配置对象中可以配置文件存储的位置和添加后缀名
    uploadDir: path.resolve(__dirname, "../upload"),//接受到文件以后,文件放到upload
    keepExtensions: true//保持后缀名
  })
  form.parse(req, async (err, params, file) => {
    //从解析的params中拿到前台传递的数据
    const {
      advTitle,
      advType,
      advOrder
    } = params;
  })

  //向数据库添加数据
  try {
    await advModel.create({
      advTitle,
      advType,
      advOrder,
      advHref: "/upload/" + file.advPic.newFilename,
      addTime: new Date().toLocaleString()
    })

    return res.send({
      code: 10000,
      msg: "添加广告成功",
      data: null
    })
  } catch (e) {
    console.log("添加广告数据库操作出现异常" + e.message);
    return res.send({
      code: 10001,
      msg: "添加广告数据库操作出现异常" + e.message,
      data: null
    })
  }
})

  
  

module.exports = route;